package com.itzg.vboxfarm.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itzg.vboxfarm.bits.Constants;
import com.itzg.vboxfarm.bits.XYPair;
import com.itzg.vboxfarm.service.HostStorageService;

@Controller
@RequestMapping("/api/hosts")
public class HostsDataController {
	private static Logger logger = LoggerFactory
			.getLogger(HostsDataController.class);
	
	@Autowired
	HostStorageService hostStorageService;
	
	@RequestMapping(value="/values/{hostId}/{metric}", method=RequestMethod.GET)
	@ResponseBody
	public Collection<XYPair<Long,Float>> getMetrics(@PathVariable long hostId, @PathVariable String metric,
			@RequestParam(defaultValue="5") int start) {
		metric = metric.replace('-', '/');
		logger.debug("Querying for data with metric name {}", metric);
		List<XYPair<Long,Float>> results = new ArrayList<XYPair<Long,Float>>();
		List<Object[]> rawData = hostStorageService.getMetricsByTime(hostId, metric, new Date(System.currentTimeMillis()-start*Constants.MSEC_PER_MINUTE));
		for (Object[] row : rawData) {
			results.add(new XYPair<Long,Float>(((Date)row[0]).getTime(), (Float)row[1]));
		}
		return results;
	}
}
